import Vue from 'vue'
import Router from 'vue-router'
import request from '../utils/request'
import store from '../store'

Vue.use(Router)

const globalRoutes = [
  // 全局路由，不需要验证是否登录
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/modules/system/login/Login')
  },
  {
    name: '404',
    path: '/404',
    component: () => import('@/views/common/404')
  }
]

const constRoutes = [
  // 静态路由，需要登录验证
  {
    name: 'main',
    path: '/',
    component: () => import('@views/common/main')
  }
]

const globalPathList = (() => {
  // 将多级结构扁平化，提取为仅有path的数组
  const list = []
  const transRoutesToList = (routes) => {
    for (const eachRoute of routes) {
      list.push(eachRoute.path)
      if ('children' in eachRoute) {
        transRoutesToList(eachRoute.children)
      }
    }
  }
  transRoutesToList(globalRoutes)
  return list
})()

const routerCreator = () => {
  return new Router({
    mode: 'hash',
    // base: routePrefix,
    // routes: globalRoutes.concat(constRoutes).concat(catchRoute)
    routes: [
      ...globalRoutes,
      ...constRoutes,
      {
        // 路由捕获，所有未匹配的路由都导到404，一定要放在最后面！
        name: 'catch',
        path: '*',
        component: () => import('@/views/common/404')
      }
    ]
  })
}

const router = routerCreator()

router.beforeEach((to, from, next) => {
  if (globalPathList.indexOf(to.path) > -1) {
    // 全局路由，不判断是否登录
    next()
  } else if (store.getters['auth/isReady']) {
    next()
  } else if (localStorage.getItem('token')) {
    request.get('/sys/user/authorities').then(({ data }) => {
      for (const menu of data.menuList) {
        router.addRoute('main', {
          name: menu.routerName,
          path: menu.routerPath,
          component: () => import('@views/modules/' + menu.routerComponent)
        })
      }
      store.commit('auth/setMenuList', data.menuList)
      store.commit('auth/setDictMap', data.dictMap)
      store.commit('auth/ready')
      next(to.fullPath, { replace: false })
    }).catch(() => {
      next({ name: 'login' })
    })
  } else {
    console.log('route,noToken')
    next({ name: 'login' })
  }
})

const routerReset = () => {
  router.matcher = routerCreator().matcher
}

export {
  routerReset
}

export default router
